<?php

function httpRequest($url, $data = '', $method = 'GET', $data_type = "")
{
    $curl = curl_init();
    if ($data_type == 'json') {
        $data = json_encode($data);
    } elseif (is_array($data)) {
        $data = http_build_query($data, '', '&');
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    // 设置连接超时时间，单位是秒
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
    // 设置请求超时时间，单位是秒
    curl_setopt($curl, CURLOPT_TIMEOUT,60);
    if ($method == 'POST') {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    // curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

function getIP()
{
    $forwarded = request()->header("x-forwarded-for");
    if ($forwarded) {
        $ip = explode(',', $forwarded)[0];
    } else {
        $ip = request()->ip();
    }
    return $ip;
}

//生成随机邀请码
function generateInviteCode($uid)
{
    $source_string = '5920638714';
    $num = $uid + 1000; // 产生4位数字
    $code = '';
    while ($num > 0) {
        $mod = $num % 10;
        $num = ($num - $mod) / 10;
        $code = $source_string[$mod] . $code;
    }
    $code = date('ym') . $code;
    return $code;
}

/**
 * 根据用户id产生token
 * @param $userId
 * @return string
 */
function generateToken($userId)
{
    return md5($userId . uniqid() . rand(0, 99999999));
}

function expire_time()
{
    return time() + 86400;
}

if (!function_exists('image_domain')) {
    /**
     * 格式化图片地址
     * @param mixed $value 图片地址
     * @param string $domain 域名
     * @return mixed|string
     */
    function image_domain($value, $domain = '')
    {
        if (empty($value)) {
            return '';
        }
        if ($domain === '') {
            $r = request();
            $domain = $r->scheme() . '://' . $r->server()['SERVER_NAME'];
        }
        if (strpos($value, 'http') === 0) {
            return $value;
        }
        return $domain . $value;
    }
}